package com.deepgames.mud.core;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.deepgames.mud.action.ActionEngine;
import com.deepgames.mud.gobject.GobjectExtractor;
import com.deepgames.mud.session.SessionManager;

public class DeepMUDServer {

	private static String propsUrl = "properties.xml";
	
	public static void main(String[] args) {
		
		GobjectExtractor gobExtr;
		SessionManager sesMan = null;
		ActionEngine actEng;
		Logger log;
		
		/*
		 * Load Properties File
		 */
		if (args.length > 0)
			propsUrl = args[1].trim();
		try {
			loadSystemProperties();
		} catch (InvalidPropertiesFormatException e1) {
			System.err.println("Invalid properties file.");
			e1.printStackTrace();
		} catch (IOException e1) {
			System.err.println("Error reading properties file.  " +  
					"File either missing or corrupt.");
			e1.printStackTrace();
		}
		
		/*
		 * Load Main Logger
		 */
		log = Logger.getLogger(DeepMUDServer.class.getName());
		log.setLevel(Level.parse(System.getProperty("deepmud.log.level")));
		
		/*
		 * Load Gobject Extractor
		 */
		gobExtr = new GobjectExtractor();
		
		/*
		 * Load Session Manager
		 */
		try {
			sesMan = new SessionManager();
		} catch (IOException e) {
			log.severe("Session Manager could not be loaded.");
			log.severe(e.toString());
			e.printStackTrace();
		}
		
		/*
		 * Load Action Engine
		 */
		actEng = new ActionEngine(sesMan, gobExtr);

		/*
		 * Start Session Manager Thread
		 */
		new Thread(sesMan).start();
		
		/*
		 * Start Action Engine (In Main Thread)
		 */
		actEng.run();
	}
	
	public static void loadSystemProperties() throws InvalidPropertiesFormatException, IOException {
		
		InputStream propsStream = null;
		Properties props = null;
		
		propsStream = new FileInputStream (propsUrl);
		
		if (propsStream != null) {
			props = new Properties();
			props.loadFromXML(propsStream);
		}
	}

}
